package com.eriloan.easyPage.plugins.templates.velocity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import com.eriloan.easyPage.util.EasyPageContext;
import com.eriloan.easyPage.util.EasyPageTools;

public class VelocityPluginsManagement{
	public static final Logger log = Logger.getLogger(VelocityPluginsManagement.class.getName());

	public static ThreadLocal<VelocityEngine> threadLocalVelocityEngine = new ThreadLocal<VelocityEngine>();

	public String getVelocityTemplate(EasyPageContext epc,Map<String,Object> ma,String vmPathName){

		try{

			HttpServletRequest req = epc.getRequest();
			HttpServletResponse res = epc.getResponse();

			res.setContentType("text/html;charset=" + epc.getCharset());

			// String projectRoot =
			// EasyPageTools.deleteRightBar(EasyPageTools.getWebProjectPath(this.getClass(),epc.getCharset()));
			String projectRoot = EasyPageTools.deleteRightBar(this.getClass().getResource(File.separator).getPath());

			String vconfPath = EasyPageContext.threadLocalTemplateConfigPath.get();

			String path = null;

			String buildKey = "/build/classes";
			String webinfoKey = "/WEB-INF/classes";
			String binKey = "/bin";

			int buildKeyInt = projectRoot.lastIndexOf(buildKey);
			int webinfoKeyInt = projectRoot.lastIndexOf(webinfoKey);
			int binKeyInt = projectRoot.lastIndexOf(binKey);

			if( - 1 != vconfPath.indexOf("WEB-INF/")){
				if( - 1 != buildKeyInt){
					path = projectRoot.substring(0,buildKeyInt) + File.separator + EasyPageContext.threadLocalEclipseContentDirectory.get() + File.separator + vconfPath;
				}

				if( - 1 != webinfoKeyInt){
					path = projectRoot.substring(0,webinfoKeyInt) + File.separator + vconfPath;
				}

				if( - 1 != binKeyInt){
					path = projectRoot + File.separator + vconfPath;
				}
			}else{
				path = projectRoot + File.separator + vconfPath;
			}

			log.log(Level.INFO,"VelocityConfigFilePath:" + path);

			File file = new File(path);
			if(file.isFile()){

				Properties p = new Properties();
				FileInputStream fileInputStream = new FileInputStream(file);
				p.load(fileInputStream);

				PrintWriter out = res.getWriter();

				VelocityEngine ve = new VelocityEngine(p);

				ve.setApplicationAttribute("javax.servlet.ServletContext",req.getSession().getServletContext());

				ve.init();

				VelocityPluginsManagement.threadLocalVelocityEngine.set(ve);

				Template template = ve.getTemplate(vmPathName,epc.getCharset());

				VelocityContext context = new VelocityContext(ma);

				StringWriter writer = new StringWriter();

				template.merge(context,writer);

				out.println(writer.toString());
				out.flush();
				out.close();
			}else{
				log.log(Level.WARNING,"Velocity configuration file can not be found.");
			}
		}catch(ResourceNotFoundException e){
			log.log(Level.WARNING,e.getMessage());
		}catch(ParseErrorException e){
			log.log(Level.WARNING,e.getMessage());
		}catch(MethodInvocationException e){
			log.log(Level.WARNING,e.getMessage());
		}catch(FileNotFoundException e){
			log.log(Level.WARNING,e.getMessage());
		}catch(IOException e){
			log.log(Level.WARNING,e.getMessage());
		}catch(Exception e){
			log.log(Level.WARNING,e.getMessage());
		}

		return vmPathName;
	}
}
